﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure
{
    /// <summary>
    /// 事件总线
    /// </summary>
    public class EventBus
    {
        /// <summary>
        /// 事件集合
        /// </summary>
        private static Dictionary<string, Action<object>> eventList = new Dictionary<string, Action<object>>();
        /// 订阅
        /// </summary>
        /// <param name="action"></param>
        public static void SubScribe(string name,Action<object> action)
        {
            eventList.Add(name,action);
        }
        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="name"></param>
        public static void UnSubScribe(string name)
        {
            eventList.Remove(name);
        }
        /// <summary>
        /// 触发执行所有订阅者
        /// </summary>
        /// <param name="obj"></param>
        public static void FireAll(object obj)
        {
            
            foreach (var action in eventList.Values)
            {
                Task.Factory.StartNew(() => {
                    action(obj);
                });
                
            }
        }
    }
}
